package com.lemon.smartsafety.ui.activity.common;

import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.common.MultiSelectItemEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectAdapter;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by Cooliean on 16/4/6.
 */
public abstract class SelectBaseActivity extends SwipeBackActivity implements RecyclerTClickListener<SelectDataI> {
    @Bind(R.id.tv_tip)
    TextView                  tvTip;
    @Bind(R.id.pullToRefreshRecyclerView)
    protected PullToRefreshRecyclerView mPullToRefreshRecyclerView;
    @Bind(R.id.multiStateView)
    MultiStateView            mMultiStateView;


    @Nullable
    @Bind(R.id.float_button)
    public FloatingActionButton mFab;

    //private LoggerHelper loggerHelper = new LoggerHelper(SelectBaseActivity.class);


    public List<SelectDataI> mDataList = new ArrayList<>();

    protected boolean isMultiSelect = false;

    public List<SelectDataI> mSelectedList = new ArrayList<>();

    protected SelectAdapter mAdapter;
    protected String oldValue = "";


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_list_refresh;
    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            oldValue = getIntent().getExtras().getString(BundleKey.OLD_SELECT_VALUE);
            isMultiSelect = getIntent().getBooleanExtra(BundleKey.IS_MULTI_SELECT, false);
            mSelectedList = (List<SelectDataI>) getIntent().getSerializableExtra(BundleKey.OLD_SELECT_VALUE_LIST);
        }
        oldValue = StringUtils.nullValue(oldValue);
        if (mSelectedList == null) {
            mSelectedList = new ArrayList<>();
        }
    }

    @Override
    protected void initViews() {
        super.initViews();
        if (isMultiSelect) {
            mAdapter = new SelectAdapter(mDataList, this, mSelectedList);
        } else {
            mAdapter = new SelectAdapter(mDataList, this, oldValue);
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);

        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });
        initMultiStateView();

        mPullToRefreshRecyclerView.beginRefreshing();


    }

    private void initMultiStateView() {
        mMultiStateView.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNetData();
            }
        });


    }


    public abstract String getTag();

    public abstract void getNetData();


    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<List> event) {
        if (getTag().equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mPullToRefreshRecyclerView.onRefreshComplete();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    httpRefresh(event.getObj());
                } else {
                    httpRefreshError(event.getMsg());
                }
            }
        }
    }


    public void httpRefresh(List data) {
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
            mDataList.clear();
            mDataList.addAll(data);
            if (isMultiSelect) {
                mAdapter.initSelectedValue();
            }
            mAdapter.notifyDataSetChanged();
        } else {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        }
    }


    public void httpRefreshError(String msg) {
        mHUDUtil.hidden();
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
        mMultiStateView.setErrorTip(msg);
    }


    @Override
    public void onItemClick(SelectDataI data, int position) {
        if (isMultiSelect) {
            SelectDataI dataI = mAdapter.setSelectedByPosition(position, !data.isSelectedI());
            addSelectVo(dataI);
        } else {
            doSingleSelect(data, position);
        }
    }

    private void addSelectVo(SelectDataI dataI) {
        if (dataI.isSelectedI()) {
            boolean hasExist = false;
            for (int i = 0; mSelectedList != null && i < mSelectedList.size(); i++) {
                SelectDataI sel = mSelectedList.get(i);
                if (sel.getValue().equals(dataI.getValue())) {
                    hasExist = true;
                    break;
                }
            }
            if (!hasExist) {
                mSelectedList.add(dataI);
            }
        } else {
            for (int i = 0; mSelectedList != null && i < mSelectedList.size(); i++) {
                SelectDataI sel = mSelectedList.get(i);
                if (sel.getValue().equals(dataI.getValue())) {
                    mSelectedList.remove(i);
                }
            }
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isMultiSelect) {
            getMenuInflater().inflate(R.menu.menu_choose, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_sure) {
            doMultiSelect();
        }
        return super.onOptionsItemSelected(item);
    }

    protected void doMultiSelect() {
        MultiSelectItemEvent event = new MultiSelectItemEvent();
        event.setTag(getTag());
        event.setData(mSelectedList);
        AppService.getBus().post(event);
        callFinish();
    }

    protected void doSingleSelect(SelectDataI data, int position) {
        SelectItemEvent event = new SelectItemEvent();
        event.setTag(getTag());
        event.setData(data);
        AppService.getBus().post(event);
        callFinish();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(getTag());
    }

}
